package top.dotgo.web.base.kit;

import cn.hutool.core.util.StrUtil;
import feign.Feign;
import feign.auth.BasicAuthRequestInterceptor;
import feign.codec.Decoder;
import feign.codec.Encoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.support.SpringMvcContract;
import org.springframework.stereotype.Component;
import top.dotgo.kit.ContextKit;
import top.dotgo.web.base.feign.BaseFeignService;

import javax.servlet.http.HttpServletRequest;

/**
 * @author jornl
 * @date 2020/2/25 23:35 星期二
 */
@Component
public class FeignKit {

    private static Encoder encoder;
    private static Decoder decoder;

    public static <T extends BaseFeignService> T getService(Class<T> clazz, String url) {
        return getService(clazz, url, true, null, null);
    }

    public static <T extends BaseFeignService> T getService(Class<T> clazz, String url, boolean isToken, String clientId, String clientSecret) {
        // options方法指定连接超时时长及响应超时时长，retryer方法指定重试策略
        Feign.Builder builder = Feign.builder();
        // 设置http 解析
        builder = builder.contract(new SpringMvcContract());
        //添加请求来源
        builder = builder.requestInterceptor(d -> d.header(JwtKit.FROM, ContextKit.getFrom().name()));

        //添加 Authorization 头
        if (!StrUtil.isEmpty(clientId) && !StrUtil.isEmpty(clientSecret)) {
            builder = builder.requestInterceptor(new BasicAuthRequestInterceptor(clientId, clientSecret));
        }
        //添加 token
        if (isToken) {
            builder = builder.requestInterceptor(d -> d.header(JwtKit.TOKEN, ContextKit.getToken()));
        }
        //设置user-agent
        builder = builder.requestInterceptor(d -> d.header("user-agent", ((HttpServletRequest) ContextKit.getRequest()).getHeader("user-agent")));

        //设置编码，不然会报错feign.codec.EncodeException
        builder = builder.encoder(encoder).decoder(decoder);
        //  target 链接目标feing，并指定访问域名
        return builder.target(clazz, url);
    }

    @Autowired
    public void setEncoder(Encoder encoder) {
        FeignKit.encoder = encoder;
    }

    @Autowired
    public void setDecoder(Decoder decoder) {
        FeignKit.decoder = decoder;
    }

}
